package com.javapda.util;

import java.io.IOException;
import java.io.InputStream;

public class ByteUtil {
	public static int byteArrayToInt(byte[] b) {
        return byteArrayToInt(b, 0);
    }

    /**
     * Convert the byte array to an int starting from the given offset.
     *
     * @param b The byte array
     * @param offset The array offset
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }
    public static int intArrayToInt(int[] b) {
    	int value=0;
    	for (int i = 0; i < b.length; i++) {
			int num = (b[i]& 0x000000FF);
//			System.out.println(num);
			int shift = (i*8);
			value += num << shift;
		}
//    	System.out.println(value);
    	return value;
    }
    
	public byte[] toBytes(long n) {
		byte[] b = new byte[8];
		b[7] = (byte) (n);
		n >>>= 8;
		b[6] = (byte) (n);
		n >>>= 8;
		b[5] = (byte) (n);
		n >>>= 8;
		b[4] = (byte) (n);
		n >>>= 8;
		b[3] = (byte) (n);
		n >>>= 8;
		b[2] = (byte) (n);
		n >>>= 8;
		b[1] = (byte) (n);
		n >>>= 8;
		b[0] = (byte) (n);

		return b;
	}
	public static byte[] toBytes(int n) {
		byte[] b = new byte[4];
		b[3] = (byte) (n);
		n >>>= 8;
		b[2] = (byte) (n);
		n >>>= 8;
		b[1] = (byte) (n);
		n >>>= 8;
		b[0] = (byte) (n);

		return b;
	}
	
	public static int[] getIntBytesFromInt(int base) {
		  int[] nums = new int[4];
		  nums[0] = base & 0x000000FF;
		  nums[1] = (base>>>8) & 0x000000FF;
		  nums[2] = (base>>>16) & 0x000000FF;
		  nums[3] = (base>>>24) & 0x000000FF;
		  return nums;
		}

	public static int readOneByte(InputStream is) throws IOException {
		int bt = is.read();
		while (bt==-1) {
			bt = is.read();
		}
		return bt;
	}
	public static int[] readMultiByte(InputStream is, int[] data) throws IOException {
//		System.out.println("READ MULTI BYTE: " + data.length);
		for (int i = 0; i < data.length; i++) {
			data[i] = readOneByte(is);
		}
		return data;
	}
	
}
